package com.mlm.mlmapp.activity;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DimensionRes;
import org.androidannotations.annotations.res.StringRes;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.activity.layoutmanager.SyGridLayoutManager;
import com.mlm.mlmapp.activity.layoutmanager.SyLayoutManager;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.GridMarginDecoration;
import com.mlm.mlmapp.adapter.view.listener.CommonItemSelectedListener;
import com.mlm.mlmapp.adapter.view.listener.DialogItemSelectedListener;
import com.mlm.mlmapp.adapter.view.listener.OnNextPageShouldDownloadListener;
import com.mlm.mlmapp.adapter.view.listener.OnRcvScrollListener;
import com.mlm.mlmapp.animation.RecyclAnimation;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.utils.CommonUtils;

@EActivity(R.layout.hairstyle_view)
public class HairStyleListActivity extends BaseActivity implements HTTPCons,
		CommonItemSelectedListener, DialogItemSelectedListener{
	public static final int DESC = 1;
	public static final int ASC = 2;
	public static final int NORMAL = 0;
	private int mPage=1;
	private AQuery aq;
	private SylistAdapter adapter;
	List<JSONObject> syListDataset;
	private TypeAdapter typeAdapter;
	private int btnStatusAttention;
	private int btnStatusCreated;
	private String currentTypeId = "";
	private boolean isMaxPage = false;
	private String currentAttention = "";
	private String currentCreated = "";
	@StringRes(R.string.all_hairstyle)
	String allHairStyle;
	@ViewById
	ImageView top;
	@ViewById
	Button btn_attention;
	@ViewById
	Button btn_created;
	@ViewById
	Button btn_hairstyle_type;
	@ViewById
	RecyclerView rv_stylist;
	@ViewById
	LinearLayout btn_back;
	@ColorRes(R.color.red)
	int redText;
	@ViewById
	RecyclerView rv_type;
	@DimensionRes(R.dimen.recyclerview_sylist_space)
	float recyclerview_sylist_space;
	private int coutPerPage = 6;

	@AfterViews
	public void init() {
		btn_back.setVisibility(View.INVISIBLE);
		btn_style.setCompoundDrawablesWithIntrinsicBounds(null, getResources()
				.getDrawable(R.drawable.stylechecked), null, null);
		btn_style.setTextColor(getResources().getColor(R.color.red));
		String title = getTitle().toString();
		if (!"".equals(title)) {
			((TextView) this.findViewById(R.id.tv_title)).setText(title);
		}

		aq = new AQuery(this);
		aq.hardwareAccelerated11();
		syListDataset = new ArrayList<>();
		LinearLayoutManager typeLayoutManager = new SyLayoutManager(this);
		rv_type.setLayoutManager(typeLayoutManager);

		final GridLayoutManager layoutManager = new SyGridLayoutManager(this, 2);
		rv_stylist.setLayoutManager(layoutManager);

		rv_stylist.addItemDecoration(new GridMarginDecoration(this,
				recyclerview_sylist_space, recyclerview_sylist_space,
				recyclerview_sylist_space, recyclerview_sylist_space));
		// rv_stylist
		// .addItemDecoration(new
		// GridMarginDecoration(this,recyclerview_sylist_space,
		// recyclerview_sylist_space, recyclerview_sylist_space,
		// recyclerview_sylist_space));
		rv_stylist.setItemAnimator(new RecyclAnimation());
		adapter = new SylistAdapter(HairStyleListActivity.this, syListDataset);
		OnRcvScrollListener listener = new OnRcvScrollListener() {

			@Override
			public void onBottom() {
				// TODO Auto-generated method stub
				super.onBottom();
				// mSwipeRefreshWidget.setRefreshing(true);
				updateDataset(mPage);
			}

		};
		rv_stylist.setOnScrollListener(listener);
		rv_stylist.setAdapter(adapter);
		// init sylist date
		updateDataset(mPage);

		aq.progress(new AQProgressDialog(this)).ajax(get_sy_type_action, JSONArray.class,
				new AjaxCallback<JSONArray>() {

					@Override
					public void callback(String url, JSONArray object,
										 AjaxStatus status) {
						// TODO Auto-generated method stub
						super.callback(url, object, status);
						if (status.getCode() == -101) {
							Toast.makeText(aq.getContext(), "网络异常,请检查网络",
									Toast.LENGTH_SHORT);
							return;
						}
						JSONObject obj = new JSONObject();
						try {

							JSONArray array = new JSONArray();
							JSONObject first = new JSONObject();
							first.put("id", "");
							first.put("clasName", allHairStyle);
							array.put(first);
							for (int i = 0; i < object.length(); i++) {
								array.put(object.getJSONObject(i));
							}
							typeAdapter = new TypeAdapter(
									HairStyleListActivity.this, array);
							rv_type.setAdapter(typeAdapter);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

				});

	}

	/**
	 * desc default,arrow up as ASC, down as DESC
	 * 
	 */
	@Click
	void btn_attention() {
		switch (btnStatusAttention) {
		case 0:
			btnStatusAttention = 1;
			currentAttention = "DESC";
			btn_attention.setCompoundDrawables(null, null, CommonUtils
					.setButtonDrawableRight(this, R.drawable.arrow_up), null);
			btn_attention.setTextColor(redText);
			break;
		case 1:
			btnStatusAttention = 2;
			currentAttention = "ASC";
			btn_attention.setCompoundDrawables(null, null, CommonUtils
					.setButtonDrawableRight(this, R.drawable.arrow_down), null);
			btn_attention.setTextColor(redText);
			break;
		case 2:
		default:
			currentAttention = "DESC";
			btnStatusAttention = 1;
			btn_attention.setCompoundDrawables(null, null, CommonUtils
					.setButtonDrawableRight(this, R.drawable.arrow_up), null);
			btn_attention.setTextColor(redText);
		}
		clearDataset();
		updateDataset(mPage);
	}

	/**
	 * desc default
	 * 
	 */
	@Click
	void btn_created() {
		switch (btnStatusCreated) {
		case 0:
			btnStatusCreated = 1;
			currentCreated = "DESC";
			btn_created.setCompoundDrawables(null, null, CommonUtils
					.setButtonDrawableRight(this, R.drawable.arrow_up), null);
			btn_created.setTextColor(redText);
			break;
		case 1:
			btnStatusCreated = 2;
			currentCreated = "ASC";
			btn_created.setCompoundDrawables(null, null, CommonUtils
					.setButtonDrawableRight(this, R.drawable.arrow_down), null);
			btn_created.setTextColor(redText);
			break;
		case 2:
		default:
			currentCreated = "DESC";

			btnStatusCreated = 1;
			btn_created.setCompoundDrawables(null, null, CommonUtils
					.setButtonDrawableRight(this, R.drawable.arrow_up), null);
			btn_created.setTextColor(redText);
		}
		clearDataset();
		updateDataset(mPage);
	}

	// when change the condition, need clear dataset
	private void clearDataset() {
		mPage=1;
		this.syListDataset.clear();
		adapter.notifyDataSetChanged();
	}

	@Click
	void btn_hairstyle_type() {

		if (rv_type.getVisibility() == View.VISIBLE)
			typeVisible(View.INVISIBLE);
		else
			typeVisible(View.VISIBLE);
	}

	void updateDataset(int page) {
		StringBuilder url = new StringBuilder(get_sy_img_action);
		url.append("?");
		if (!"".equals(currentAttention)) {
			url.append("collect=" + currentAttention);
			url.append("&");
		}

		if (!"".equals(currentCreated)) {
			url.append("created=" + currentCreated);
			url.append("&");
		}
		if (!"".equals(currentTypeId)) {
			url.append("clasId=" + currentTypeId);
			url.append("&");
		}
		url.append("page=" + page);
		getSylist(url.toString());

	}

	void getSylist(String url) {
		aq.progress(new AQProgressDialog(this)).ajax(url, JSONArray.class, new AjaxCallback<JSONArray>() {

			@Override
			public void callback(String url, JSONArray object, AjaxStatus status) {
				// TODO Auto-generated method stub
				super.callback(url, object, status);
				if (status.getCode() == -101) {
					Toast.makeText(aq.getContext(), "网络异常,请检查网络",
							Toast.LENGTH_SHORT);
					return;
				}
				if (object != null && object.length() > 0) {
					for (int i = 0; i < object.length(); i++) {
						try {
							syListDataset.add(object.getJSONObject(i));
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					mPage++;
					adapter.notifyDataSetChanged();
				}
			}

		});

	}

	class SylistAdapter extends
			Adapter<SylistAdapter.SyViewHolder> {
		private CommonItemSelectedListener mOnCommonItemSelectedListener;
		List<JSONObject> array;
		Context con;
		private int nextPageFlag = 6;

		public SylistAdapter(Context con, List<JSONObject> array) {
			this.con = con;
			this.mOnCommonItemSelectedListener = (CommonItemSelectedListener) con;
			this.array = array;

		}

		public String getID(int position) {

			JSONObject currObj = array.get(position);
			return CommonUtils.getJsonString(currObj, "id");

		}

		@Override
		public int getItemCount() {
			return array.size();
		}

		class SyViewHolder extends ViewHolder implements OnClickListener {
			TextView tv_sy_intro;
			ImageView iv_sy_img;

			public SyViewHolder(View view) {
				super(view);
				tv_sy_intro = (TextView) view.findViewById(R.id.tv_sy_intro);
				iv_sy_img = (ImageView) view.findViewById(R.id.iv_sy_img);
				iv_sy_img.setOnClickListener(this);
			}

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mOnCommonItemSelectedListener.onItemClick(arg0, getPosition());
			}
		}

		@Override
		public SyViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
			// TODO Auto-generated method stub
			SyViewHolder holder = new SyViewHolder(LayoutInflater.from(
					HairStyleListActivity.this).inflate(
					R.layout.hair_style_list_item, parent, false));
			return holder;
		}

		@Override
		public void onBindViewHolder(SyViewHolder holder, int position) {
			// TODO Auto-generated method stub
			JSONObject obj = array.get(position);
			aq.id(holder.iv_sy_img).image(
					CommonUtils.getJsonString(obj, "hairPhotoUrl"), true, true,
					150, 0, null, Constants.FADE_IN);
			holder.tv_sy_intro.setText(CommonUtils.getJsonString(obj,
					"infoDescription"));

		}



	}

	class TypeAdapter extends Adapter<TypeAdapter.TypeViewHolder> {
		private DialogItemSelectedListener mOnDialogItemSelectedListener;
		JSONArray array;
		Context con;

		public TypeAdapter(Context con, JSONArray array) {
			this.con = con;
			this.mOnDialogItemSelectedListener = (DialogItemSelectedListener) con;
			this.array = array;

		}

		public String getID(int position) {
			try {
				return CommonUtils.getJsonString(array.getJSONObject(position),
						"id");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}

		}

		@Override
		public int getItemCount() {
			return array.length();
		}

		class TypeViewHolder extends ViewHolder implements OnClickListener {
			TextView tv_sy_intro;

			public TypeViewHolder(View view) {
				super(view);
				tv_sy_intro = (TextView) view.findViewById(R.id.tv_dialog_item);
				tv_sy_intro.setClickable(true);
				tv_sy_intro.setOnClickListener(this);
			}

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mOnDialogItemSelectedListener.onDialogItemClick(arg0,
						getPosition());
			}
		}

		@Override
		public TypeViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
			// TODO Auto-generated method stub
			TypeViewHolder holder = new TypeViewHolder(LayoutInflater.from(
					HairStyleListActivity.this).inflate(
					R.layout.dialog_header_item_view, parent, false));
			return holder;
		}

		@Override
		public void onBindViewHolder(TypeViewHolder holder, int position) {
			// TODO Auto-generated method stub

			try {
				JSONObject obj = array.getJSONObject(position);
				holder.tv_sy_intro.setText(CommonUtils.getJsonString(obj,
						"clasName"));

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	@Override
	public void onItemClick(View v, int position) {
		// TODO Auto-generated method stub

		HairStyleDetailActivity_
				.intent(this)
				.extra("id",
						CommonUtils.getJsonString(syListDataset.get(position),
								"id")).start();
	}

	@Override
	public void onDialogItemClick(View v, int position) {
		// TODO Auto-generated method stub
		typeAdapter = (TypeAdapter) rv_type.getAdapter();
		currentTypeId = typeAdapter.getID(position);
		typeVisible(View.INVISIBLE);
		clearDataset();
		updateDataset(mPage);
	}

	// as the function name !

	private void typeVisible(int flag) {
		if (flag == View.INVISIBLE) {
			rv_type.setVisibility(View.INVISIBLE);
			top.setVisibility(View.INVISIBLE);
		} else {
			rv_type.setVisibility(View.VISIBLE);
			top.setVisibility(View.VISIBLE);
		}
	}

	@Click
	void btn_home() {
		MainActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
	}

	@Click
	void btn_dresser() {
		HairDresserListActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
	}

	@Click
	void btn_appointment() {
		BookActivity_.intent(this).start();
	}

	@ViewById
	Button btn_style;

	@Click
	void btn_style() {
		// HairStyleListActivity_.intent(this).start();

	}

	@Click
	void btn_userinfo() {
		UserInfoActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
	}


	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent data = new Intent();
		setResult(RESULT_CANCELED, data);
		this.finish();
	}
}
